package com.jun.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;

import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

@Configuration
public class JacksonConfig {

  private static final String DATE = "yyyy-MM-dd";
  private static final String DATETIME = "yyyy-MM-dd HH:mm:ss";

  @Bean
  @Order(Ordered.HIGHEST_PRECEDENCE)
  public Jackson2ObjectMapperBuilderCustomizer customizer() {
    return (builder) -> {
      builder.serializerByType(LocalDate.class,
          new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE)));
      builder.serializerByType(LocalDateTime.class,
          new LocalDateSerializer(DateTimeFormatter.ofPattern(DATETIME)));

      builder.serializationInclusion(JsonInclude.Include.NON_NULL);
      builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);
    };
  }

  @Bean
  public ObjectMapper objectMapper() {
    ObjectMapper om =  new ObjectMapper();
    om.setDateFormat(new SimpleDateFormat(DATE));
    om.setTimeZone(TimeZone.getTimeZone("GMT+8"));
    om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

    JavaTimeModule jtm = new JavaTimeModule();
    jtm.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE)));
    jtm.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATETIME)));

    om.registerModule(jtm);

    return om;
  }

}
